<template>
  <el-dialog
    v-model="open" title="长租会员" width="800px" append-to-body :close-on-click-modal="false"
    @close="cancel"
  >
    <el-form ref="longRentQueryRef" :model="queryParams" :rules="queryRules" label-width="100px">
      <el-form-item label="会员" prop="memberId">
        <span>{{ queryParams.memberName }}</span>
        <el-button class="ml20" type="text" @click="openMemberList">+选择会员</el-button>
      </el-form-item>

      <el-form-item label="选择场地" prop="siteIdArr">
        <el-select v-model="queryParams.siteIdArr" multiple>
          <el-option v-for="s in siteList" :key="s.id" :label="s.name" :value="s.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="时间段" prop="orderTimeRange">
        <el-time-select
          v-model="queryParams.orderTimeStart"
          :max-time="queryParams.orderTimeEnd"
          class="mr-4"
          placeholder="00:00"
          :start="venStore.businessPeriod[0]"
          :end="venStore.businessPeriod[1]"
        />
        <span> 至 </span>
        <el-time-select
          v-model="queryParams.orderTimeEnd"
          :min-time="queryParams.orderTimeStart"
          class="mr-4"
          placeholder="00:00"
          :start="venStore.businessPeriod[0]"
          :end="venStore.businessPeriod[1]"
        />
      </el-form-item>

      <el-form-item label="周期" prop="weekIndex">
        <el-checkbox-group v-model="queryParams.weekChecked">
          <el-checkbox v-for="w in weekList" :key="w" :label="w" />
        </el-checkbox-group>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="getDateRange">获取可预定的时间范围</el-button>
      </el-form-item>
    </el-form>

    <el-form ref="longRentRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="会员余额">
        <span class="cRed">￥{{ balance }}</span>
      </el-form-item>
      <el-form-item label="可预订日期" prop="orderDate">
        <el-date-picker v-model="form.orderDate" type="daterange" range-separator="~" :disabled-date="disabledDate" />
      </el-form-item>

      <el-form-item label="备注"><el-input v-model="form.remark" type="textarea" /></el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">预订场地</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
  <!--选择会员-->
  <SelectMember v-model="openMember" @chooseMember="chooseMember" />

</template>

<script setup>
import { getCurrentInstance, reactive } from '@vue/runtime-core'
import useVenStore from '../../../../../../store/modules/ven'
import { toRefs } from '@vueuse/shared'
import { getSiteList } from '@/api/ven'
import { computed } from '@vue/reactivity'
import { backLongRentSite, generateCanOrderDate, saveReserveInfo } from '@/api/ven/reserve'
import { watch } from 'vue'
import SelectMember from './selectMember'
import { dayjs } from 'element-plus'


const venStore = useVenStore()
const { proxy } = getCurrentInstance()

const emit = defineEmits(['update:modelValue', 'submitForm'])

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const queryParamsBase = {
  memberId: '',
  projectId: '',
  siteIdArr: [],
  orderTimeStart: '',
  orderTimeEnd: '',
  weekChecked: []
}
const formBase = {
  orderDate: ''
}
const data = reactive({
  queryParams: {
    ...queryParamsBase
  },
  queryRules: {
    memberId: {
      validator: (rule, value, callback) => {
        if (!value) {
          callback('必填')
        } else {
          callback()
        }
      }, required: true
    },
    siteIdArr: {
      validator: (rule, value, callback) => {
        if (value.length === 0) {
          callback('必填')
        } else {
          callback()
        }
      }, required: true },
    orderTimeRange: {
      validator: (rule, value, callback) => {
        if (!queryParams.value.orderTimeStart || !queryParams.value.orderTimeEnd) {
          callback('必填')
        } else {
          callback()
        }
      }, required: true
    },
    weekIndex: {
      validator: (rule, value, callback) => {
        if (queryParams.value.weekChecked.length === 0) {
          callback('必填')
        } else {
          callback()
        }
      }, required: true
    }
  },
  form: {
    ...formBase
  },
  rules: {
    orderDate: { required: true, message: '必填' }
  },
  weekList: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
  openMember: false,
  siteList: [],
  balance: ''
})
const { queryParams, queryRules, form, rules, weekList, openMember, siteList, balance } = toRefs(data)

const open = computed({
  get: () => props.modelValue,
  set: () => {}
})
watch(open, val => {
  getSites()
  if (val) {
    queryParams.value = { ...queryParamsBase }
    form.value = { ...formBase }
  } else {
    proxy.resetForm('longRentQueryRef')
    proxy.resetForm('longRentRef')
    balance.value = ''
  }
})

watch(queryParams, () => {
  form.value = { ...formBase }
}, { deep: true })

function getSites() {
  // queryParams.value.siteId = ''
  getSiteList().then(res => {
    siteList.value = res.rows
  })
}

function getDateRange() {
  proxy.$refs['longRentQueryRef'].validate((valid) => {
    if (valid) {
      const weekIndex = []
      _.each(weekList.value, (w) => {
        if (_.some(queryParams.value.weekChecked, (v) => v === w)) {
          weekIndex.push(1)
        } else {
          weekIndex.push(0)
        }
      })
      queryParams.value.weekIndex = weekIndex.join(',')
      queryParams.value.orderTimeRange = [queryParams.value.orderTimeStart, queryParams.value.orderTimeEnd].join(',')
      queryParams.value.siteId = queryParams.value.siteIdArr.join(',')
      generateCanOrderDate(queryParams.value).then((res) => {
        const temp = res.data.orderDate.split(',')
        form.value.minTime = temp[0]
        form.value.maxTime = temp[1]
        form.value.orderDate = [dayjs(temp[0]), dayjs(temp[1])]
      })
    }
  })
}

function disabledDate(time) {
  let disabled = false

  if (form.value.minTime) {
    if (time.getTime() < dayjs(form.value.minTime).valueOf()) {
      disabled = true
    }
  } else {
    if (time.getTime() < dayjs().add(-1, 'day').valueOf()) {
      disabled = true
    }
  }

  if (form.value.maxTime && !disabled) {
    if (time.getTime() > dayjs(form.value.maxTime).valueOf()) {
      disabled = true
    }
  }
  return disabled
}

function submitForm() {
  proxy.$refs['longRentRef'].validate(valid => {
    if (valid) {
      backLongRentSite(_.assign({}, queryParams.value, {
        orderDateRange: [dayjs(form.value.orderDate[0]).format('YYYY-MM-DD'), dayjs(form.value.orderDate[1]).format('YYYY-MM-DD')].join(',')
      })).then(() => {
        proxy.$modal.msgSuccess('操作成功')
        emit('update:modelValue', false)
        emit('submitForm')
      })
    }
  })
}

function cancel() {
  emit('update:modelValue', false)
}

function openMemberList() {
  openMember.value = true
}
// 选择会员
function chooseMember(member) {
  queryParams.value.memberId = member.id
  queryParams.value.memberName = member.memberName

  balance.value = member.balance
}

</script>

<style scoped></style>
